<template>
	<div class="standardmanage">
		<div class="mainCon">
			<div class="containercontent">
				<div class="treeDivStyle inlineblock">
					<div class="oprate">
						<!--物资类型-->
						<el-button type="primary" size="mini" @click="dealItem(itemInfo)" style="float:right;margin-right:5px;" v-if="userOpernation.delete.display" :disabled="!itemInfo.hasOwnProperty('id')" >删除</el-button>
						<el-button @click="copyAbilityColition(itemInfo)" style="float:right;margin-right:5px;margin-left:0;" type="primary" size="mini" v-if="userOpernation.update.display" :disabled="!itemInfo.hasOwnProperty('id')">复制</el-button>
						<el-button @click="editAbilityColition(itemInfo)"  style="float:right;margin-right:5px;margin-left:0;" type="primary" size="mini" v-if="userOpernation.update.display" :disabled="!itemInfo.hasOwnProperty('id')">编辑</el-button>
						<el-button type="primary" size="mini" @click="addItem" style="float:right;margin-right:5px;"  v-if="userOpernation.add.display" >添加</el-button>

					</div>
					<el-input  v-model="filterText" size="mini" placeholder="项目集" style="margin-bottom: 8px;"> </el-input>
					<el-tree :data="abilityColitionTableDate" :props="defaultProps" :filter-node-method="filterNode" @node-click="handleNodeClick" ref="treeBox" node-key="id" :default-checked-keys="arrHight"
					:expand-on-click-node="false" default-expand-all :highlight-current="true">
					<span class="custom-tree-node" slot-scope="{ node, data }" style="color: #000;">
						<!-- {{data}} -->
						<span>
							<i :class="node.icon"  style="margin-right:5px" v-if="data.subcontractor == '' || !data.hasOwnProperty('subcontractor') "></i>
							<i :class="node.icon"  style="margin-right:5px;color: blue;"  v-if="data.subcontractor != '' && data.hasOwnProperty('subcontractor') "></i>
							{{node.label}}
						</span>
						
					</span>
					</el-tree>
				</div>
				<div class="inlineblock treeRightCon">
					<div class="seachTip selectw100">
						<div class="inlineblock verticalmiddle infoitem">
						<div class="inlineblock verticalmiddle">
							检测项目
						</div>
						<div class="inlineblock verticalmiddle informationItem">
							<el-select v-model="searchName" clearable filterable size="mini" @change = "doSearch">
							<el-option v-for="item in itemList" :key="item.item" :label="item.itemName" :value="item.item">
							</el-option>
							</el-select>
							<!-- <el-input v-model="searchName"  size="mini" placeholder="检测项目" @keyup.enter.native="doSearch"></el-input> -->
						</div>
						</div>
						<div class="inlineblock verticalmiddle infoitem">
						<div class="inlineblock verticalmiddle">
							能力参数状态
						</div>
						<div class="inlineblock verticalmiddle informationItem" style="width: calc(100% - 82px);">
							<el-select v-model="status" clearable size="mini" @change = "doSearch">
							<el-option key="1" label="启用" value="1"></el-option>
							<el-option key="0" label="停用" value="0"></el-option>
							</el-select>
						</div>
						</div>
						<div class="inlineblock basicRightDistanceA searchIcon">
						<el-button size="mini" @click="doSearch">搜索</el-button>
						<!-- <el-button size="mini" @click="emptySearch">清空</el-button> -->
						</div>
					</div>
					<div class="separaterowTable">
						<div class="tableTittle">
						<div style="margin-right:20px;"><span class="fontImpact">1</span><span>检测项目【{{counts}}】</span></div>
						<span class="purpose" v-if="itemInfo.hasOwnProperty('subcontractorName') && itemInfo.subcontractorName !=''"><span style="color: #999;">分包商 :</span> {{itemInfo.subcontractorName}}</span>
						<span class="purpose" v-if="itemInfo.hasOwnProperty('purpose') && itemInfo.purpose !=''"><span style="color: #999;">用途 :</span> {{itemInfo.purpose}}</span>

						<el-button type="primary" icon="el-icon-plus" size="mini" style="float:right;" @click="addability" v-if="userOpernation.add.display" :disabled="!itemInfo.hasOwnProperty('id')">添加项目</el-button>

						</div>
						<el-table :data="ItemSetInfosTableDate" style="width: 100%" class="tableCon" size="mini">
							<el-table-column label="序号" min-width="50px">
								<template slot-scope="scope">
									{{scope.$index+(itemQuery.page - 1) * itemQuery.pageCount + 1}}
								</template>
							</el-table-column>
							<el-table-column property="itemNames" label="检测项目" min-width="200px" show-overflow-tooltip>
							</el-table-column>
							<el-table-column label="能力参数" property="detectabilityName" min-width="200px" show-overflow-tooltip>
							</el-table-column>
							<el-table-column label="状态" property="status" min-width="120px">
								<template slot-scope="scope">
									<span v-if="scope.row.status == 0" style="color:red;">已停用</span>
									<span v-if="scope.row.status == 1">已启用</span>
								</template>
							</el-table-column>
							<el-table-column label="操作" min-width="100px">
								<template slot-scope="scope">
									<el-button type="text" size="mini" @click="delAbility(scope.row)" v-if="userOpernation.delete.display">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<div class="block changepages">
							<el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :current-page="itemQuery.page" :page-sizes="[20, 50, 100, 500]"
							:page-size="itemQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
							</el-pagination>
						</div>
					</div>
				</div>
			</div>
		</div>
		<el-dialog :close-on-click-modal="false" :visible.sync="addItemShow" width="50%" :show-close='false'>
			<span slot="title" class="dialog-title">
		  	{{itemTitle}}
			    <el-button @click="addItemShow = false" size="mini" class="popupClose">关闭</el-button>
			  </span>
			<el-form :inline="true" class="demo-form-inline formItemData" label-width = "90px" ref="formItemData" :model="formItemData" :rules="rules">

				<el-form-item label="集合名称:" style="width:88%;" prop="name">
					<el-input placeholder="集合名称" size="mini" v-model="formItemData.name" style = "width:100%"></el-input>
				</el-form-item>
				<el-form-item label="集合用途:" style="width:88%;" prop="purpose" >
					<el-input size="mini" placeholder="集合用途" v-model="formItemData.purpose"  style = "width:100%" ></el-input>
				</el-form-item>
				<el-form-item label="分包商:" style="width:88%;" prop="subcontractor">
					<el-select clearable filterable v-model="formItemData.subcontractor" placeholder="分包商" size='mini'  style = "width:100%" :disabled = "itemTitle == '编辑集合'">
						<el-option v-for="item in subData" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="doItemAddEdit" size="mini">确 定</el-button>
			    <el-button @click="addItemShow = false" size="mini">取 消</el-button>
			  </span>
		</el-dialog>
		<ability-item :addVisible.sync="addabilityShow" :readItem="readItem"></ability-item>
		<copy-item :addVisible.sync="copyabilityShow" :formItemData = "itemData" ></copy-item>
	</div>

</template>

<script>
	import { mapState } from 'vuex'
	const abilityItem = () =>
  import("./children/abilityItem.vue");
  const copyItem = () =>
  import("./children/copyItem.vue");

	export default {
		data() {
			let that = this;
			return {
				selectAbility: [], //选中的能力参数
				selectItem: [], //选中的检测项目
				enableStatusValue: '',
				methodCategoryValue: '',
				methodTypeValue: '',
				ablityName: '',
				abilityBeanList: [], //能力参数
				multipleSelecInd: 0,
				multipleSelections: [],//右边选中的检测项和分析项总和[0:[],1:[]]
				reload: true,
				rules: {
					name: [{ required: true, message: '请填写名字', trigger: 'blur' }]
				},
				currentPage: 1,
				//    集合参数
				addItemShow: false,
				itemTitle: "添加集合",
				readItemParams: { //集合查询条件
					name: '',
				},
				readQuery: {
					page: 1,
					pageCount: 20,
				},
				rowNumber0: 0,
				formItemData: { //集合添加参数
					name: '',
					purpose: '',
					subcontractor:'',
				},
				isShow: false,
				abilityColitionTableDate: [], //集合列表列表数据
				//    集合详情参数
				readItem: {},
				addabilityShow: false,
				itemSetInfosTitle: "添加检测项目",
				itemSetInfosParams: {
					id: '',
					page: 1,
					pageCount: 20,
				},
				itemQuery: {
					page: 1,
					pageCount: 20,
				},
				rowNumber: 0,
				subData:[],


				infosisShow: true,
				ItemSetInfosTableDate: [], //集合详情列表数据

				itemBeanList: [], //项目集合数据列表
				detects: [], //能力参数数据列表
				abilityTableDate: [], //添加检测项目数组数据
				abilityChangedItem: '', //
				copyabilityShow:false,//复制检测项目
				itemData:{}, //复制时，选中的数据下面的能力参数和检测项

        defaultProps: {  //项目集树继承的值
          label: 'name',
          value: 'id'
        },
        arrHight: [], //树高亮显示的数组
        itemInfo:{},
        searchName:"",
        filterText:"",
        itemList:[],
        counts:0,
        status:""

			}
		},
		computed: {
			...mapState(['enableStatus', 'tableHeightC', 'monitorPointBigType', 'sampleType', 'methodCategory', 'methodType', 'mainEquipType', 'frontEquipType']),
		},
		props: ['userOpernation'],
		beforeCreate() {

		},
		mounted() {
			this.readItemSet()
		},
		components: {
			abilityItem,copyItem
		},
		watch: {
			itemQuery: {
				handler(val, oldVal) {
					this.getItemSetInfos()
				},
				deep: true
			},
			readQuery: {
				handler(val, oldVal) {
					this.readItemSet()
				},
				deep: true
			},
      filterText(val) {
        this.$refs.treeBox.filter(val);
      }
		},
		methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      // renderContent (h, { node, data, store }) {
      //   console.log(node,data)
      //   return (
      //   `<span>
      //     <i :class='{data.icon}'></i>
      //     <span> {node.data.name}</span>
      //   </span>`
      //   )
      // },
      //  点击物资类型树
      handleNodeClick(val) {
         this.itemInfo = val;
         this.searchName = '';
         this.status = "";
         this.arrHight.push(val.id);
         this.$nextTick(() => {
           this.$refs.treeBox.setCurrentKey(val.id);// treeBox 元素的ref   value 绑定的node-key

         });
         this.itemSetInfosParams.fRef = val.id;
         this.readItem = val
         this.getNums();
         this.doSearch()
      },
			doSearch() {
				this.itemQuery.page = 1;
				this.getItemSetInfos();
			},

			readItemSet() {
				var params = this.readItemParams;
				this.$http({
					method: 'post',
					apiUrl: '/detection/readItemSet.htm',
					params: params,
					isJson: true,
				}).then(res => {
					if (res.code === 0) {
            res.data.forEach((item) =>{
              this.$set(item,'icon','el-icon-document')
            })
            this.abilityColitionTableDate = [{
              label:"项目集",
              name:"项目集",
              children:res.data
            }];

						this.isShow = true;

						if (res.data.length == 0) {
							this.ItemSetInfosTableDate = [];
							this.rowNumber = 0;
						} else {
							this.handleNodeClick(res.data[0]);
						}
						if (!res.pageinfo) {
							this.rowNumber0 = 0;
						} else if (res.pageinfo && !res.pageinfo.rowNumber) {
							this.rowNumber0 = 0;
						} else {
							this.rowNumber0 = res.pageinfo.rowNumber;
						}
					}
				}, )
			},

			//	集合添加修改以及删除方法
			addItem() {
				this.itemTitle = "添加集合";
				this.addItemShow = true;
				this.formItemData = { //集合添加参数
					name: '',
					subcontractor:"",
					purpose: ''
				};
				this.getSubconts();
			},
			copyAbilityColition(row){
				this.$http({
					method: 'post',
					apiUrl: '/detection/getSetAllDetects.htm',
					params: {
						id: row.id,
					},
					isJson: false,
				}).then(res => {
					if (res.code === 0) {
						console.log(res.data)

						this.itemData = res.data;
						this.copyabilityShow = true;

					}
				})
			},
			editAbilityColition: function (row) {
				this.itemTitle = "编辑集合";
				this.formItemData.name = row.name;
				this.formItemData.purpose = row.purpose;
				this.formItemData.subcontractor = row.subcontractor,
				this.formItemData.id = row.id;
				this.addItemShow = true;
				this.getSubconts();

			},
			// 获取项目集
			getSubconts() {
				// 获取项目集
				this.$http({
					method: 'post',
					apiUrl: '/resource/getSubconts.htm',
				}).then(res => {
					if (res.code === 0) {
						this.subData = res.data
					}
				})
			},
			doItemAddEdit() {
				this.$refs.formItemData.validate((valid) => { //表单验证
					if (valid) {
						let url = ''
						if (this.itemTitle == "添加集合") {
							url = '/detection/addItemSet.htm'
						} else if (this.itemTitle == "编辑集合") {
							url = '/detection/updateItemSet.htm'
						}
						this.$http({
							method: 'post',
							apiUrl: url,
							params: this.formItemData,
							isJson: true,
						}).then(res => {
							if (res.code === 0) {
								this.addItemShow = false;
								this.readItemSet()
								if (this.itemTitle == "添加集合") {
									this.$message({
										showClose: true,
										message: '添加成功！',
										type: 'success'
									})
								} else if (this.itemTitle == "修改集合") {
									this.$message({
										showClose: true,
										message: '修改成功！',
										type: 'success'
									})
								}

							}
						})
					} else {
						return false;
					}
				})


			},
			// 删除集合
			dealItem(row) {
				this.$confirm('是否删除', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						method: 'post',
						apiUrl: '/detection/deleteItemSet.htm',
						params: {
							id: row.id
						},
						isJson: false,
					}).then(res => {
						if (res.code === 0) {
							this.readItemSet()
							this.$message({
								showClose: true,
								message: '删除成功！',
								type: 'success'
							})
						}
					}, )
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});

			},
			// 删除能力参数检测项目
			delAbility(row) {
				this.$confirm('是否删除', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						method: 'post',
						apiUrl: '/detection/deleteItemSetDetect.htm',
						params: {
							id: row.id
						},
						isJson: false,
					}).then(res => {
						if (res.code === 0) {
							this.$message({
								showClose: true,
								message: '删除成功！',
								type: 'success'
							})
							this.getItemSetInfos()
              this.getNums();
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});

			},
			saveAbilityRequest(params) {
				return new Promise((resolve, reject) => {
					this.$http({
						method: 'post',
						apiUrl: '/detection/updateItemSetInfo.htm',
						params: params,
						isJson: true,
					}).then(res => {
						if (res.code === 0) {
							resolve(res)
						} else {
							reject(err)
						}
					}, )
				})
			},
			reloadInfos() {
				this.infosisShow = false;
				this.$nextTick(() => {
					this.infosisShow = true;
				})
			},
      getNums(){
        this.$http({
        	method: 'post',
        	apiUrl: '/detection/getItemNums.htm',
        	params: {id:this.readItem.id},
        	isJson: false,
        }).then(res => {
        	if (res.code === 0) {
            this.itemList = res.data.list;
            this.counts = res.data.total;
          }
        })
      },
			// 获取详细信息
			getItemSetInfos() {
				this.$http({
					method: 'post',
					apiUrl: '/detection/getItemSetDetects.htm',
					params: {
						fRef: this.readItem.id,
						page: this.itemQuery.page,
						pageCount: this.itemQuery.pageCount,
            item:this.searchName,
            detectStatus:this.status != '' ? Number(this.status):null
					},
					isJson: true,
				}).then(res => {
					if (res.code === 0) {
						this.ItemSetInfosTableDate = res.data;
						this.infosisShow = true;
						if (!res.pageinfo) {
							this.rowNumber = 0;
						} else if (res.pageinfo && !res.pageinfo.rowNumber) {
							this.rowNumber = 0;
						} else {
							this.rowNumber = res.pageinfo.rowNumber;
						}

					}
				})
			},
			handleSizeChange: function (val) {
				this.readQuery.pageCount = val;
			},
			handleCurrentChange: function (val) {
				this.readQuery.page = val;
			},
			handleSizeChange1(val) {
				this.itemQuery.pageCount = val;
			},
			handleCurrentChange1(val) {
				this.itemQuery.page = val;
			},
			/**
			 * 添加检测项目方法**
			 */
			//	添加检测项目以及获取检测项目数据集合
			addability() {
				// this.readitemBeanList();
				this.abilityTableDate = [];
				this.detects = [];
				this.addabilityShow = true
			},
			//			添加检测项目条目
			addDetect() {
				this.abilityTableDate.push({
					fRef: this.itemSetInfosParams.fRef,
					item: '',
					detectability: ''
				});
				this.detects.push([])

			},
			//删除检测项目条目
			delDetect(aIndex) {
				this.$delete(this.abilityTableDate, aIndex)
				this.$delete(this.detects, aIndex)

			},
			//校验检测项目信息
			checkabilityTableDate() {
				let count = 0;
				for (let item of this.abilityTableDate) {
					for (let item2 in item) {
						if (item[item2] == '') {
							count++
						}
					}
				}
				if (count > 0) {
					return false
				} else {
					return true
				}
			},

			// 删除能力参数
			deleteItem(index) {
				this.itemBeanList.splice(index, 1);
			},
			//保存检测项目信息
			saveDetects() {
				this.$http({
					method: 'post',
					apiUrl: '/detection/addItemSetInfos.htm',
					params: this.selectItem,
					isJson: true,
				}).then(res => {
					if (res.code === 0) {
            this.getItemSetInfos();
						this.addabilityShow = false
						this.$message({
							showClose: true,
							message: '保存成功！',
							type: 'success'
						})
					}
				})

			},


			//		检测项目下拉框选中事件
			itemBeanListChange(scope) {
				let defaultAbility = this.itemBeanList.filter(item => item.id === scope.row.item)
				if (defaultAbility[0].hasOwnProperty('detectability')) {
					scope.row.detectability = defaultAbility[0].detectability
					//					this.$set(scope, 'detectability', defaultAbility[0].detectability)
				} else {
					scope.row.detectability = ''
				}
				console.log(scope)
				this.chooseDetectByItem(scope.row.item, scope.$index).then(res => {
					if (res.data.length == 1) {
						scope.row.detectability = res.data[0].id
					}
					this.$set(this.detects, scope.$index, res.data)

				})
			},
			//		获取能力参数
			chooseDetectByItem(ItemBeanId, index) {
				return new Promise((resolve, reject) => {
					//做一些异步操作
					this.$http({
						method: 'post',
						apiUrl: '/technology/chooseDetectByItem.htm',
						params: {
							item: ItemBeanId
						},
						isJson: false,
					}).then(res => {
						if (res.code === 0) {
							resolve(res)
						} else {
							//			          	reject(err)
						}
					}, )
				});

			},
		}
	}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.separaterow {
		margin-top: 10px;
	}
  .tableTittle>div{
    width: 140px;
  }

	.informationItem {
		width: calc(100% - 70px);
		float: right;
	}
  .seachTip .infoitem {
      width: calc(100%/3);
      line-height: 25px;
  }
  .treeDivStyle {
    width: 25%;
    height: 100%;
    background: #fff;
  }
  .treeDivStyle .el-tree{
      height: calc(100% - 85px);
      overflow-y: scroll;
      overflow-x: auto;
  }
  .treeRightCon {
    margin-left: 10px;
    width: calc(74% - 10px);
    height: 100%;
    vertical-align: top;
  }

  .treeDivStyle .oprate {
    height: 40px;
    padding-top: 3px;
    /* border-bottom: 1px solid #dadada; */
  }
  .purpose{
    display: inline-block;
    width: 150px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

</style>
<style>
	.formItemData.demo-form-inline .el-form-item .el-form-item__content{
		width:calc(100% - 90px) !important;
	}
  .colorBlue{
    color: #409eff;
  }
</style>
